/**
 * Copyright 2013 yangming.liu<liuyangming@gmail.com>.
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, see <http://www.gnu.org/licenses/>.
 */
package org.bytesoft.openjta.xa;

import java.io.Serializable;
import java.util.Arrays;

import javax.transaction.xa.Xid;

import org.bytesoft.utils.ByteUtils;

public class GlobalXidImpl extends XidImpl implements Xid, Serializable {
	private static final long serialVersionUID = 1L;

	protected byte[] globalTransactionId;

	public GlobalXidImpl() {
		this(new byte[0]);
	}

	public GlobalXidImpl(byte[] global) {
		if (global == null) {
			throw new IllegalArgumentException("The globalTransactionId cannot be null.");
		} else if (global.length > Xid.MAXGTRIDSIZE) {
			throw new IllegalArgumentException("The length of globalTransactionId cannot be greater than 64.");
		}

		this.globalTransactionId = global;
	}

	@Override
	public byte[] getBranchQualifier() {
		return new byte[0];
	}

	@Override
	public byte[] getGlobalTransactionId() {
		return this.globalTransactionId;
	}

	@Override
	public int hashCode() {
		int hash = 17;
		hash += formatId;
		hash += Arrays.hashCode(globalTransactionId);
		return hash;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		} else if (obj == null) {
			return false;
		} else if (getClass() != obj.getClass()) {
			return false;
		}
		GlobalXidImpl other = (GlobalXidImpl) obj;
		if (formatId != other.formatId) {
			return false;
		} else if (!Arrays.equals(globalTransactionId, other.globalTransactionId)) {
			return false;
		}
		return true;
	}

	@Override
	public String toString() {
		String global = null;
		if (this.globalTransactionId != null) {
			global = ByteUtils.byteArrayToString(this.globalTransactionId);
		}
		return String.format("%s-%s", this.formatId, global);
	}

	@Override
	public XidImpl getGlobalXid() {
		return this;
	}

}
